﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Player
{
    public class StreamReader
    {
        Stream m_stream;
        BinaryReader m_br;
        bool m_networkOrder;

        public long Position
        {
            get { return m_stream.Position; }
        }

        public StreamReader(Stream stream, bool networkOrder)
        {
            m_stream = stream;
            m_br = new BinaryReader(m_stream);
            m_networkOrder = networkOrder;
        }

        public int GetInt32()
        {
            int temp = m_br.ReadInt32();
            return m_networkOrder ? System.Net.IPAddress.NetworkToHostOrder(temp) : temp;
        }

        public short GetInt16()
        {
            short temp = m_br.ReadInt16();
            return m_networkOrder ? System.Net.IPAddress.NetworkToHostOrder(temp) : temp;
        }

        public string GetString()
        {
            int len = GetInt32();
            byte[] temp = m_br.ReadBytes(len);
            return System.Text.Encoding.UTF8.GetString(temp);
        }

        public byte[] GetBytes()
        {
            int len = GetInt32();
            return m_br.ReadBytes(len);
        }

        public byte GetByte()
        {
            return m_br.ReadByte();
        }

        public byte[] GetCompressedBytes()
        {
            Int32 len = GetInt32();
            byte[] temp = m_br.ReadBytes(len);
            return temp;
        }

        public byte[] GetRawBytes(int len)
        {
            return m_br.ReadBytes(len);
        }

        public int Read(byte[] buffer, int index)
        {
            int len = GetInt32();

            int readCount = 0;

            do
            {
                readCount += m_br.Read(buffer, index + readCount, len - readCount);
            } while (readCount < len);

            return len;
        }

        public int Read(byte[] buffer, int index, int count)
        {
            return m_br.Read(buffer, index, count);
        }

        public byte[] GetRemainingBytes()
        {
            int numBytes = (int)(m_stream.Length - m_stream.Position);
            byte[] ret = new byte[numBytes];
            m_stream.Read(ret, 0, numBytes);
            return ret;
        }

        public long GetInt64()
        {
            long temp = m_br.ReadInt64();
            return m_networkOrder ? System.Net.IPAddress.NetworkToHostOrder(temp) : temp;

        }

        public bool IsAtEnd()
        {
            return m_stream.Position >= m_stream.Length;
        }

        public void Seek(long offset, SeekOrigin location)
        {
            m_stream.Seek(offset, location);
        }

    }
}
